package com.youth.framework.util;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieUtils {
	
	/**
	 * 将cookie封装到Map中
	 * @param request
	 * @return
	 */
	private static Map<String,Cookie> getCookieMap(HttpServletRequest request){
		Map<String,Cookie> cookieMap = new HashMap<String,Cookie>();
		
		Cookie[] cookies = request.getCookies();

		if(null!=cookies){
			for(Cookie cookie:cookies){
				cookieMap.put(cookie.getName(), cookie);
			}
		}
		
		return cookieMap;
	}
	
	/**
	 * 根据名字获取cookie
	 * @param request
	 * @param name
	 * @return
	 */
	public static Cookie getCookieByName(HttpServletRequest request,String name){
		Cookie cookie = null;
		
		Map<String,Cookie> cookieMap = getCookieMap(request);
		
		if(cookieMap.containsKey(name)){
			cookie = cookieMap.get(name);
		}
		
		return cookie;
	}
	
	/**
	 * 添加一个cookie
	 * @param response
	 * @param name
	 * @param value
	 * @param maxAge
	 */
	public static void addCookie(HttpServletResponse response,String name,String value,int maxAge){
	    Cookie cookie = new Cookie(name,value);
	    cookie.setPath("/");
	    if(maxAge>0)  cookie.setMaxAge(maxAge);
	    response.addCookie(cookie);
	}
}
